package org.yoao.crm.tools;

import java.util.UUID;

import org.yoao.crm.dao.CustomerDAO;
import org.yoao.moneymachine.dao.OrderDAO;
import org.yoao.moneymachine.dao.UserDAO;

/**
 * @author yxwonline.com
 * @description 获取客户码
 * @date 2010-8-1 下午01:22:55
 */
public class CodeFactory {
	
	public synchronized static final String getCostomerCodeUUID(){
		return getUUID();
	}
	
	public synchronized static final String getUUID(){
		return UUID.randomUUID().toString();
	}
	
	public synchronized static final String getCostomerCodeBySQL()throws Exception{
		CustomerDAO customerDAO = new CustomerDAO();
		String customerCode = customerDAO.findMaxCustomerCode();
		if(customerCode == null || customerCode.trim().equals("")){
			customerCode = "YC0000000001";
		}else{
			int number = Integer.parseInt(customerCode.substring(2));
			customerCode = String.valueOf(number + 1);
			if(customerCode.length() < 10){
				int length = 10 - customerCode.length();
				for(int i=0;i<length;i++){
					customerCode = "0" + customerCode;
				}
			}
			customerCode = "YC" + customerCode;
		}
		return customerCode;
	}
	
	public synchronized static final String getOrderNumberBySQL()throws Exception{
		OrderDAO orderDAO = new OrderDAO();
		String orderNumber = orderDAO.findMaxOrderNumber();
		if(orderNumber == null || orderNumber.trim().equals("")){
			orderNumber = "YO000000000000001";
		}else{
			int number = Integer.parseInt(orderNumber.substring(2));
			orderNumber = String.valueOf(number + 1);
			if(orderNumber.length() < 15){
				int length = 10 - orderNumber.length();
				for(int i=0;i<length;i++){
					orderNumber = "0" + orderNumber;
				}
			}
			orderNumber = "YO" + orderNumber;
		}
		return orderNumber;
	}
	
	public synchronized static final String getExpandCode() throws Exception{
		StringBuffer code = new StringBuffer();
		for(int i=0;i<8;i++){
			int tmp = (int)(Math.random()*26+65);
			char c = (char)tmp;
			code.append(c);
		}
		UserDAO userDAO = new UserDAO();
		String userCode = userDAO.findByUserCode(code.toString().toLowerCase());
		if(userCode == null || userCode.trim().equals("") || userCode.equals("0"))
			return code.toString().toLowerCase();
		else{
			return getExpandCode();
		}
	}
}